/**
 * Model.java Object.
 * 
 * @author Le Duc, Nam(lenam.k54@gmail.com)
 * @version 0.1
 */
package com.arena.model;

import org.json.JSONException;
import org.json.JSONObject;

public class Model {
	Fetcher fetcher;
	JSONObject jsData;
	String sData;
	String host;
	/**
	 * Initialize local variable
	 */
	public Model(String sHost) {		
		// initialize data
		jsData = new JSONObject();
		sData = "{date:\"lenam\"}";		
		host = sHost;
	}
	/**
	 * Use fetcher to get data from server
	 */
	public void fetch() {
		final Model local = this;
		// create fetcher with callback function
		fetcher = new Fetcher(){
			@Override
			protected void onPostExecute(String result) {			
				super.onPostExecute(result);
				local.onPostExecute(result);
			}
		};
		fetcher.execute(host);
	}
	/**
	 * This function will be called after this model get data from server
	 */
	public void onPostExecute(String result) {
		try {
			jsData = parseJSON(result);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	/**
	 * Get field in JSON object of this model
	 * @param fieldName - name of field which you want to get
	 * @return 
	 * 		- null: if field is not exists
	 * 		- Object: data of field
	 */
	public Object getField(String fieldName) {
		try {
			return jsData.get(fieldName);			
		} catch (JSONException e) {		
			e.printStackTrace();
			return "";
		}
		
	}
	/**
	 * Parse string to JSON object 
	 * @param data - string which you want to parse to JSON object
	 * @return JSON object
	 * @throws JSONException 
	 */
	private JSONObject parseJSON(String data) throws JSONException {
		JSONObject jsonData = new JSONObject(data);
		return jsonData;
	}
}
